package com.tech.connect.zhaofuwu;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.request.RequestOptions;
import com.ksy.common.image.ImageLoader;
import com.ksy.common.image.ImageOptions;
import com.ksy.common.image.ImageShowActivity;
import com.ksy.common.image.transformations.RoundedCornersTransformation;
import com.ksy.common.utils.AndroidUtil;
import com.ksy.common.utils.BaseAdapter;
import com.ksy.common.utils.BaseHolder;
import com.ksy.common.utils.DateUtil;
import com.ksy.common.view.GridOffsetsItemDecoration;
import com.ksy.common.view.ProxyLayout;
import com.ksy.common.view.PullToRefreshLayout;
import com.tech.connect.R;
import com.tech.connect.activity.EditTextActivity;
import com.tech.connect.api.BaseEntityOb;
import com.tech.connect.api.HttpUtils;
import com.tech.connect.api.ImageApi;
import com.tech.connect.api.QuznZiHttp;
import com.tech.connect.api.UserInfo;
import com.tech.connect.fragment.BaseFragment;
import com.tech.connect.model.ItemComment;
import com.tech.connect.model.ItemQuznZi;
import com.tech.connect.model.PagerModel;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class QuanZiImageFragment extends BaseFragment {

    private BaseAdapter<ItemQuznZi, BaseHolder> adapter;
    private RecyclerView recycler;
    private List<ItemQuznZi> allList = new ArrayList<>();
    private int page = 1;
    private int pageSize = 15;
    private ProxyLayout<RecyclerView> proxyLayout;
    private int height;
    private View header;

    @Override
    protected boolean isShowHeadBar() {
        return true;
    }

    @Override
    protected boolean isFullStateBar() {
        return true;
    }

    @Override
    public View onCreateView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.layout_recycler, null);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getHeadBar().setLeftIcon(R.drawable.icon_back, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (activity != null) {
                    activity.onBackPressed();
                }
            }
        }).setTitle("服务圈").setRightText("发布", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jump2Activity(PublishQuanZiActivity.class, 996);
            }
        });
        height = AndroidUtil.dip2px(80);

        initView(view);
        loadData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (requestCode == 996) {
            if (Activity.RESULT_OK == resultCode) {
                page = 1;
                loadData();
            }
        } else if (requestCode == 995) {
            if (Activity.RESULT_OK == resultCode) {
                String data = intent.getStringExtra("data");
                int position = intent.getIntExtra("position", -1);
                Serializable extra = intent.getSerializableExtra("extra");
                if (position >= 0 && position < allList.size() && extra instanceof ItemQuznZi) {
                    ItemQuznZi itemQuznZi = (ItemQuznZi) extra;
                    comment(data, itemQuznZi, position);
                }
            }
        }
    }

    private void initView(View view) {
//        View rootLayout = view.findViewById(R.id.rootLayout);
        recycler = view.findViewById(R.id.recycler);
        header = LayoutInflater.from(activity).inflate(R.layout.header_quanzi_image, null);
        recycler.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return true;
            }
        });
//        recycler.addItemDecoration(new HLineDivider(Color.parseColor("#00000000"),10));
        proxyLayout = new ProxyLayout<>(activity, recycler);
        proxyLayout.setCanRefresh(true);
        proxyLayout.setDragListener(new PullToRefreshLayout.DragListener() {
            @Override
            public void drag2Upper(PullToRefreshLayout pullToRefreshLayout) {
                ++page;
                loadData();
            }

            @Override
            public void drag2Downer(PullToRefreshLayout pullToRefreshLayout) {
                page = 1;
                loadData();
            }
        });
    }


    private void initAdapter(List<ItemQuznZi> list) {
        if (list != null) {
            allList.addAll(list);
        }
        if (adapter == null) {
            adapter = new BaseAdapter<ItemQuznZi, BaseHolder>(R.layout.item_layout_quanzi_image, allList) {
                @Override
                public int getItemViewType(int position) {
                    if (position == 0) {
                        return -1;
                    }
                    return 1;
                }

                @Override
                public int getItemCount() {
                    return allList.size() + 1;
                }

                @Override
                public BaseHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    BaseHolder baseHolder;
                    if (viewType == 1) {
                        View inflate = LayoutInflater.from(parent.getContext()).inflate(itemLayoutId, parent, false);
                        baseHolder = new BaseHolder(inflate);
                    } else {
                        baseHolder = new BaseHolder(header);
                    }
                    return baseHolder;

                }

                @Override
                protected void convert(BaseHolder helper, final int poi) {
                    if (poi == 0) {
                        View mine = helper.getView(R.id.mine);
                        mine.setVisibility(View.GONE);
                        ImageView ivCover = helper.getView(R.id.ivCover);
                        TextView tvName = helper.getView(R.id.tvName);
                        ImageView ivHead = helper.getView(R.id.ivHead);
                        tvName.setText(UserInfo.getUserInfo().nickName);
                        ImageLoader.getInstance().load(activity, UserInfo.getUserInfo().backgroundImage, ivCover, new RequestOptions().centerCrop());
                        ImageLoader.getInstance().load(activity, UserInfo.getUserInfo().headImage, ivHead, new RequestOptions().transform(new RoundedCornersTransformation(AndroidUtil.dip2px(5))));
                        return;
                    }
                    final int position = poi - 1;
                    final ItemQuznZi item = allList.get(position);
                    ImageView ivHead = helper.getView(R.id.ivHead);
                    TextView tvName = helper.getView(R.id.tvName);
                    TextView tvCity = helper.getView(R.id.tvCity);
                    TextView tvContent = helper.getView(R.id.tvContent);
                    RecyclerView recyclerImage = helper.getView(R.id.recyclerImage);
                    TextView tvDate = helper.getView(R.id.tvDate);
                    TextView tvPraise = helper.getView(R.id.tvPraise);
                    TextView tvComment = helper.getView(R.id.tvComment);
                    TextView tvShare = helper.getView(R.id.tvShare);
                    TextView tvChat = helper.getView(R.id.tvChat);
                    RecyclerView recyclerComment = helper.getView(R.id.recyclerComment);

                    String headUrl = "";
                    String userName = "";
                    String cityName = "";
                    if (item.obj != null && item.obj.user != null) {
                        headUrl = item.obj.user.headImage;
                        userName = item.obj.user.nickName;
                        cityName = item.obj.user.cityName;
                    }
                    ImageLoader.getInstance().loadHead(activity, headUrl, ivHead, new RequestOptions().transform(new RoundedCornersTransformation(AndroidUtil.dip2px(5))));
                    tvName.setText(userName);
                    tvCity.setText(cityName);
                    if (isEmpty(item.content)) {
                        tvContent.setVisibility(View.GONE);
                    } else {
                        tvContent.setVisibility(View.VISIBLE);
                    }
                    tvContent.setText(item.content);
                    final ArrayList<String> images = ImageApi.getImages(item.images);
                    if (images.isEmpty()) {
                        recyclerImage.setVisibility(View.GONE);
                    } else {
                        BaseAdapter adapter = new BaseAdapter<String, BaseHolder>(R.layout.item_rect_image, images) {
                            @Override
                            protected void convert(BaseHolder helper, final int innerPosition) {
                                ViewGroup.LayoutParams layoutParams = helper.itemView.getLayoutParams();
                                if (layoutParams == null) {
                                    layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
                                }
                                layoutParams.height = height;
                                layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                                helper.itemView.setLayoutParams(layoutParams);
                                ImageView imageView = helper.getView(R.id.image);
                                imageView.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        ImageShowActivity.showImages(activity, images, innerPosition);
                                    }
                                });
                                ImageLoader.getInstance().load(activity, images.get(innerPosition), imageView, new ImageOptions().centerCrop());

                            }
                        };
                        recyclerImage.setAdapter(adapter);
                        RecyclerView.LayoutManager layoutManager = recyclerImage.getLayoutManager();
                        if (layoutManager == null) {
                            layoutManager = new GridLayoutManager(activity, 3, GridLayoutManager.VERTICAL, false);
                            recyclerImage.setLayoutManager(layoutManager);
                        }
                        GridOffsetsItemDecoration offsetsItemDecoration = new GridOffsetsItemDecoration(
                                GridOffsetsItemDecoration.GRID_OFFSETS_VERTICAL);
                        offsetsItemDecoration.setVerticalItemOffsets((int) AndroidUtil.dip2px(5));
                        offsetsItemDecoration.setHorizontalItemOffsets((int) AndroidUtil.dip2px(5));
                        int itemDecorationCount = recyclerImage.getItemDecorationCount();
                        if (itemDecorationCount <= 0) {
                            recyclerImage.addItemDecoration(offsetsItemDecoration);
                        }
                        recyclerImage.setVisibility(View.VISIBLE);
                    }

                    tvDate.setText(DateUtil.getSmartDate(item.createTime));
                    String praise = "点赞";
                    String comment = "评论";
                    if (item.obj != null) {
                        if (item.obj.likeCount > 0) {
                            praise += "(" + item.obj.likeCount + ")";
                        }
                        if (item.obj.commentCount > 0) {
                            comment += "(" + item.obj.commentCount + ")";
                        }
                    }
                    tvPraise.setText(praise);
                    tvComment.setText(comment);
                    tvPraise.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            praise(item, position);
                        }
                    });
                    tvComment.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(activity, EditTextActivity.class);
                            intent.putExtra("extra", item);
                            intent.putExtra("position", position);
                            jump2Activity(intent, 995);
                        }
                    });
                    tvShare.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    });
                    tvChat.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    });

                    final List<ItemComment> comments = new ArrayList<>();
                    if (item.obj != null && item.obj.comments != null) {
                        comments.addAll(item.obj.comments);
                    }
                    if (comments.isEmpty()) {
                        recyclerComment.setVisibility(View.GONE);
                    } else {
                        BaseAdapter adapter = new BaseAdapter<ItemComment, BaseHolder>(R.layout.item_layout_quanzi_comment, comments) {
                            @Override
                            protected void convert(BaseHolder helper, final int innerPosition) {
                                ItemComment item = comments.get(innerPosition);
                                TextView tvName = helper.getView(R.id.tvName);
                                TextView tvContent = helper.getView(R.id.tvContent);
                                tvName.setText(item.typeName);
                                tvContent.setText(item.content);
                            }
                        };
                        recyclerComment.setAdapter(adapter);
                        RecyclerView.LayoutManager layoutManager = recyclerComment.getLayoutManager();
                        if (layoutManager == null) {
                            layoutManager = new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false);
                            recyclerComment.setLayoutManager(layoutManager);
                        }
                        recyclerComment.setVisibility(View.VISIBLE);
                    }
                }
            };
            adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
//                    Intent intent = new Intent(activity, ZhaoFuWuLvYouViewActivity.class);
//                    intent.putExtra("lvYouTitle", "苹果6s");
//                    jump2Activity(intent);
                }
            });
            recycler.setAdapter(adapter);
        }
        adapter.notifyDataSetChanged();
    }


    private void loadData() {
        Map<String, Object> map = QuznZiHttp.getMap();
        map.put("containsImage", 1);
        map.put("containsVideo", 0);
        map.put("pageNumber", page);
        map.put("pageSize", pageSize);
        QuznZiHttp.list(map, new BaseEntityOb<PagerModel<ItemQuznZi>>() {
            @Override
            public void onDataDeal(boolean isSuccess, PagerModel<ItemQuznZi> data, String msg) {
                List<ItemQuznZi> list = null;
                if (isSuccess && data != null) {
                    list = data.content;
                }
                if (page == 1) {
                    allList.clear();
                }
                initAdapter(list);
                if (list != null && list.size() >= pageSize) {
                    proxyLayout.setCanLoadMore(true);
                } else {
                    proxyLayout.setCanLoadMore(false);
                }
                if (allList.isEmpty()) {
                    proxyLayout.showEmptyView();
                } else {
                    proxyLayout.showContentView();
                }
                proxyLayout.dragFinish();
            }
        });
    }

    private void praise(final ItemQuznZi item, final int position) {
        Map<String, Object> map = HttpUtils.getMap();
        map.put("id", item.id);
        map.put("type", 50);
        HttpUtils.praise(map, new BaseEntityOb<Integer>() {
            @Override
            public void onStart() {
                super.onStart();
                showDialog();
            }

            @Override
            public void onDataDeal(boolean isSuccess, Integer data, String msg) {
                hideDialog();
                showToast(msg);
                if (item.obj == null) {
                    item.obj = new ItemQuznZi.Extra();
                }
                item.obj.likeCount = data;
                adapter.notifyItemChanged(position);
            }
        });
    }

    private void comment(String data, final ItemQuznZi item, final int position) {
        Map<String, Object> map = HttpUtils.getMap();
        map.put("content", data);
        map.put("typeId", item.id);
        map.put("type", 50);
        HttpUtils.comment(map, new BaseEntityOb<Object>() {
            @Override
            public void onStart() {
                super.onStart();
                showDialog();
            }

            @Override
            public void onDataDeal(boolean isSuccess, Object data, String msg) {
                hideDialog();
                showToast(msg);
//                if (item.obj == null) {
//                    item.obj = new ItemQuznZi.Extra();
//                }
//                item.obj.likeCount = data;
//                adapter.notifyItemChanged(position);
            }
        });
    }
}